// 背景脚本 - 处理扩展逻辑

// 存储检测到的资源
let detectedResources = {};

// 连接到本地应用（Native Messaging）
let port = null;

// 初始化
chrome.runtime.onInstalled.addListener(() => {
    console.log('SwiftShadow 扩展已安装');

    // 创建右键菜单
    chrome.contextMenus.create({
        id: 'download-with-swiftshadow',
        title: '使用疾影下载',
        contexts: ['link', 'video', 'audio']
    });
});

// 监听网络请求（嗅探资源）
chrome.webRequest.onBeforeRequest.addListener(
    (details) => {
        const url = details.url;
        const type = details.type;

        // 检测媒体资源
        if (isMediaResource(url, type)) {
            const tabId = details.tabId;

            if (!detectedResources[tabId]) {
                detectedResources[tabId] = [];
            }

            // 去重
            if (!detectedResources[tabId].find(r => r.url === url)) {
                detectedResources[tabId].push({
                    url: url,
                    type: getResourceType(url),
                    timestamp: Date.now()
                });

                // 更新徽章
                updateBadge(tabId);

                console.log('检测到媒体资源:', url);
            }
        }
    },
    {urls: ["<all_urls>"]}
);

// 判断是否为媒体资源
function isMediaResource(url, type) {
    const mediaTypes = ['media', 'video', 'audio'];
    const mediaExtensions = ['.mp4', '.webm', '.m3u8', '.mpd', '.mp3', '.m4a', '.flv', '.ts'];

    if (mediaTypes.includes(type)) {
        return true;
    }

    return mediaExtensions.some(ext => url.toLowerCase().includes(ext));
}

// 确定资源类型
function getResourceType(url) {
    const urlLower = url.toLowerCase();

    if (urlLower.includes('.m3u8')) return 'm3u8';
    if (urlLower.includes('.mpd')) return 'mpd';
    if (urlLower.includes('.mp4') || urlLower.includes('.webm')) return 'video';
    if (urlLower.includes('.mp3') || urlLower.includes('.m4a')) return 'audio';

    return 'unknown';
}

// 更新徽章
function updateBadge(tabId) {
    const count = detectedResources[tabId]?.length || 0;

    if (count > 0) {
        chrome.action.setBadgeText({
            tabId: tabId,
            text: count.toString()
        });
        chrome.action.setBadgeBackgroundColor({
            tabId: tabId,
            color: '#FF4444'
        });
    }
}

// 右键菜单点击处理
chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === 'download-with-swiftshadow') {
        const url = info.linkUrl || info.srcUrl;

        if (url) {
            sendToNativeApp({
                action: 'download',
                url: url,
                title: tab.title,
                pageUrl: tab.url
            });
        }
    }
});

// 监听来自popup或content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'getResources') {
        const tabId = request.tabId;
        sendResponse({resources: detectedResources[tabId] || []});
    } else if (request.action === 'downloadResource') {
        sendToNativeApp({
            action: 'download',
            ...request.data
        });
        sendResponse({success: true});
    } else if (request.action === 'clearResources') {
        const tabId = request.tabId;
        detectedResources[tabId] = [];
        updateBadge(tabId);
        sendResponse({success: true});
    }

    return true; // 保持消息通道开放
});

// 发送消息到本地应用（Native Messaging）
function sendToNativeApp(message) {
    try {
        if (!port) {
            port = chrome.runtime.connectNative('com.swiftshadow.downloader');

            port.onDisconnect.addListener(() => {
                console.log('与本地应用的连接已断开');
                port = null;
            });
        }

        port.postMessage(message);
        console.log('已发送消息到本地应用:', message);
    } catch (error) {
        console.error('连接本地应用失败:', error);
    }
}

// 标签页关闭时清理
chrome.tabs.onRemoved.addListener((tabId) => {
    delete detectedResources[tabId];
});